-- 顶点数据组装器
-- 参照了一下cocos creator 但是做成了类，靠类的实例去做每个渲染对象的顶点数据缓存
Assembler = Assembler or Class("Assembler")
local tmpTransform = love.math.newTransform()

---@diagnostic disable-next-line: duplicate-set-field
function Assembler:ctor(renderer)
    self.renderer = renderer
end
function Assembler:getVerticePositions()
    local owner = self.renderer
    if self._vertexDirty or not self._verticePositions then
        owner:checkUpdateTransform()
        tmpTransform:setTransformation(owner.wx, owner.wy, owner.wr, owner.wsx, owner.wsy, 0, 0, owner.kx, owner.ky)
        local left = -owner.ax * owner.width
        local top = -owner.ay * owner.height
        local right = owner.width + left
        local bottom = top + owner.height
        self._verticePositions = {
            {tmpTransform:transformPoint(left, top)},
            {tmpTransform:transformPoint(right, top)},
            {tmpTransform:transformPoint(right, bottom)},
            {tmpTransform:transformPoint(left, bottom)}
        }
        self._vertexDirty = false
    end
    return self._verticePositions
end
local _uvs = {
    0,
    0,
    1,
    0,
    1,
    1,
    0,
    1
}
function Assembler:getUVs()
    return _uvs
end
function Assembler:getVerticeColors()
    if not self._colors or self._colorDirty then
        local r, g, b, a = self.renderer:rgba()
        self._colors = {r, g, b, a, r, g, b, a, r, g, b, a, r, g, b, a}
        self._colorDirty = false
    end
    return self._colors
end
local map = {1, 2, 3, 1, 3, 4}
function Assembler:getVertexMap()
    return map
end

function Assembler:getVertices()
    if not self._vertices or self.dirty then
        local vertices = {}
        local positions = self:getVerticePositions()
        local colors = self:getVerticeColors()
        local uvs = self:getUVs()
        for i, v in ipairs(positions) do
            local tbl = {
                v[1],
                v[2],
                uvs[(i - 1) * 2 + 1],
                uvs[i * 2],
                colors[(i - 1) * 4 + 1],
                colors[(i - 1) * 4 + 2],
                colors[(i - 1) * 4 + 3],
                colors[(i - 1) * 4 + 4]
            }
            table.insert(vertices, tbl)
        end
        self._vertices = vertices
        self.dirty = false
    end

    return self._vertices
end

function Assembler:setVertexDirty()
    self.dirty = true
    self._vertexDirty = true
end

function Assembler:setColorDirty()
    self.dirty = true
    self._colorDirty = true
end
